import { personalFuncs } from '@/system/api/sysApi'
import Layout from '@/layout'
import templatePage from '@/system/pages/customPage/templatePage'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
	if (route.meta && route.meta.roles) {
		return roles.some(role => route.meta.roles.includes(role))
	} else {
		return true
	}
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes) {
	const res = []

	routes.forEach(item => {
		let route = {
			path: `/${item.packId}`,
			name: `${String(item.packId)}`,
			meta: {
				title: item.packName,
			},
			component: Layout,
		}
		if (item.funcList) {
			route.children = filterFuncList(item.funcList)
		}
		res.push(route)
	})
	return res
}
const name = 'templatePage'
function filterFuncList(list) {
	let funcList = []
	let route = {}
	list.forEach(item => {
		let path = item.wmName
		if (path) {
			let index = path.indexOf(name)
			if (index !== -1) {
				let id = path.substr(index + name.length + 1, path.length)
				route = {
					path: `/t${id}/:id`,
					name: `t${id}`,
					component: templatePage,
					props: true,
					meta: {
						title: item.name,
						keepAlive: false,
						funcId: item.funcId,
					},
				}
			} else {
				route = {
					path,
					name: item.name,
					props: true,
					meta: {
						title: item.name,
						keepAlive: false,
						funcId: item.id,
						wfClassId: item.wfClassId,
						permi: [],
					},
				}
				if (item.autList && item.autList.length > 0) {
					item.autList.forEach(aut => {
						route.meta.permi.push(aut.code)
					})
				}
				route.component = loadView(item.pagePath1)
			}
			funcList.push(route)
		}
	})
	return funcList
}

export const loadView = view => {
	if (process.env.NODE_ENV === 'development') {
		return resolve => require([`@/${view.slice(1)}`], resolve)
	} else {
		// 使用 import 实现生产环境的路由懒加载
		return () => import(`@/${view.slice(1)}`)
	}
}

const state = {
	routes: [],
	addRoutes: [],
}

const mutations = {
	SET_ROUTES: (state, routes) => {
		state.addRoutes = routes
		state.routes = routes
	},
}

const actions = {
	generateRoutes({ commit }, routerList) {
		return new Promise(resolve => {
			let accessedRoutes = filterAsyncRoutes(routerList)
			// }
			commit('SET_ROUTES', accessedRoutes)
			resolve(accessedRoutes)
		})
	},
	loadPermission() {
		return new Promise((resolve, reject) => {
			personalFuncs({ name: null })
				.then(res => {
					if (res.success) {
						resolve(res.info)
					} else {
						resolve(res)
					}
				})
				.catch(error => {
					reject(error)
				})
		})
	},
}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
}
